package myTest.chat.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class User implements Runnable {
	private Socket s;
	private static final String path = "/home/chenwei/Document/";

	User(Socket s) {
		this.s = s;
	}

	public void run() {
		try {
			String ip = s.getInetAddress().getHostAddress();

			System.out.println(ip + ".....connected");

			BufferedInputStream socIn = new BufferedInputStream(s.getInputStream());

			BufferedOutputStream fileBinWriter = new BufferedOutputStream(new FileOutputStream(path + ip + ".jpg"));

			PrintWriter socOut = new PrintWriter(s.getOutputStream(), true);

			for (int data; (data = socIn.read()) != -1;)
				fileBinWriter.write(data);
			fileBinWriter.flush();

			socOut.println("上传成功");

			fileBinWriter.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class Server {
	public static void main(String[] args) {
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(10005);
			while (true) {
				System.out.println("accpting");
				Socket s = ss.accept();
				new Thread(new User(s)).start();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			System.out.println("finally running");
			if (ss != null)
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}